

#include "../SourceCode/muduo/include/TcpServer.hpp"
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

size_t Split(const std::string &src, const std::string &sep, std::vector<std::string> *arr)
{
    size_t offset = 0;
    while (offset < src.size())
    {
        size_t pos = src.find(sep, offset);
        if (pos == std::string::npos)
        {
            arr->push_back(src.substr(offset));
            return arr->size();
        }
        if (pos != offset)
            arr->push_back(src.substr(offset, pos - offset));
        offset = pos + sep.size();
    }
    return arr->size();
}

void test_Split()
{
    // std::string str = ",,,,,,,,,,,,abc,,,,,bcd,,,,,def,";
    // std::string str = ",,,,,,,,,,,,abc,,,,,bcd,,,,,def";
    std::string str = "def";
    std::vector<std::string> arr;
    int ret = Split(str, ",", &arr);
    std::cout << str << std::endl;
    std::cout << ret << std::endl;
    for (auto& e : arr)
    {
        std::cout << "[" <<  e << "]" << std::endl;
    }
}

bool ReadFile(const std::string& file_name, std::string* content)
{
    std::ifstream ifs(file_name, std::ios::binary);
    if (ifs.is_open() == false)
    {
        LOG(ERROR, "Util::ReadFile Failed to open file %s, errno: %d -> %s\n", file_name.c_str(), errno, strerror(errno));
        return false;
    }
    LOG(HDEBUG, "Util::ReadFile open file %s success\n", file_name.c_str());
    ifs.seekg(0, ifs.end);
    size_t file_size = ifs.tellg();
    ifs.seekg(0, ifs.beg);

    content->resize(file_size);
    ifs.read(&((*content)[0]), file_size);
    if (ifs.good() == false)
    {
        LOG(ERROR, "Util::ReadFile Failed to read from file %s, errno: %d -> %s\n", file_name.c_str(), errno, strerror(errno));
        ifs.close();
        return false;
    }
    LOG(HDEBUG, "Util::ReadFile read from file %s success\n", file_name.c_str());
    ifs.close();
    return true;
}

bool WriteFile(const std::string& file_name, const std::string& content)
{
    std::ofstream ofs(file_name, std::ios::binary | std::ios::trunc);
    if (ofs.is_open() == false)
    {
        LOG(ERROR, "Util::WriteFile Failed to open file %s, errno: %d -> %s\n", file_name.c_str(), errno, strerror(errno));
        return false;
    }
    LOG(HDEBUG, "Util::WriteFile open file %s success\n", file_name.c_str());

    ofs.write(content.c_str(), content.size());
    if (ofs.good() == false)
    {
        LOG(ERROR, "Util::WriteFile Failed to write into file %s, errno: %d -> %s\n", file_name.c_str(), errno, strerror(errno));
        ofs.close();
        return false;
    }
    ofs.close();
    LOG(HDEBUG, "Util::ReadFile write into file %s success\n", file_name.c_str());
    return true;
}

void test_ReadFile(std::string* content)
{
    
    bool ret = ReadFile("timewheel.cc", content);
    if (ret == false) return;
    // std::cout << res << std::endl;
}

void test_WriteFile(std::string& content)
{

    bool ret = WriteFile("hahahahahahaha.txt", content);
    if (ret == false) return;
    // std::cout << res << std::endl;
}


std::string UrlEncode(const std::string url, bool convert_space_to_plus)
{
    std::string res;
    for (auto& c : url)
    {
        if (isalpha(c) || isalnum(c) || c == '-' || c == '_' || c == '~' || c == '.')
        {
            res += c;
            continue;
        }
        else if (c == ' ' && convert_space_to_plus)
        {
            res += '+';
            continue;
        }
        else
        {
            // 转换为 %HH 格式 
            char tmp[4] = { 0 };
            snprintf(tmp, sizeof tmp, "%%%02X", c);
            res += tmp;
        }
    }
    return res;
}

char HEX_TO_DEC(char c)
{
    if (isdigit(c)) return c - '0';
    else if (isupper(c)) return c - 'A' + 10;
    else if (islower(c)) return c - 'a' + 10;
    else LOG(WARNING, "Util::UrlDecode URL Formatting error!\n");
    return -1;
}

std::string UrlDecode(const std::string url, bool convert_plus_to_space)
{
    std::string res;
    for (int i = 0; i < url.size(); ++i)
    {
        if (url[i] == '%')
        {
            unsigned char v1 = HEX_TO_DEC(url[i + 1]);
            unsigned char v2 = HEX_TO_DEC(url[i + 2]);
            res += (v1 * 16 + v2);
            i += 2;
        }
        else if (isalnum(url[i]) || url[i] == '-' || url[i] == '_' || url[i] == '~' || url[i] == '.')
        {
            res += url[i];
            continue;
        }
        else if (url[i] == '+' && convert_plus_to_space)
        {
            res += ' ';
            continue;
        }
    }
    return res;
}

void test_Url()
{
    std::string res;
    std::string url = "/login?user=how&passwd=C  ";
    // std::string url = "C++";
    std::cout << "[" << (res = UrlEncode(url, true)) << "]" << std::endl;
    std::cout << "[" << UrlDecode(res, true) << "]" << std::endl;
}



std::string GetStatuDesc(int statu)
{
    std::unordered_map<int, std::string> _statu_msg = {
        {100,  "Continue"},
        {101,  "Switching Protocol"},
        {102,  "Processing"},
        {103,  "Early Hints"},
        {200,  "OK"},
        {201,  "Created"},
        {202,  "Accepted"},
        {203,  "Non-Authoritative Information"},
        {204,  "No Content"},
        {205,  "Reset Content"},
        {206,  "Partial Content"},
        {207,  "Multi-Status"},
        {208,  "Already Reported"},
        {226,  "IM Used"},
        {300,  "Multiple Choice"},
        {301,  "Moved Permanently"},
        {302,  "Found"},
        {303,  "See Other"},
        {304,  "Not Modified"},
        {305,  "Use Proxy"},
        {306,  "unused"},
        {307,  "Temporary Redirect"},
        {308,  "Permanent Redirect"},
        {400,  "Bad Request"},
        {401,  "Unauthorized"},
        {402,  "Payment Required"},
        {403,  "Forbidden"},
        {404,  "Not Found"},
        {405,  "Method Not Allowed"},
        {406,  "Not Acceptable"},
        {407,  "Proxy Authentication Required"},
        {408,  "Request Timeout"},
        {409,  "Conflict"},
        {410,  "Gone"},
        {411,  "Length Required"},
        {412,  "Precondition Failed"},
        {413,  "Payload Too Large"},
        {414,  "URI Too Long"},
        {415,  "Unsupported Media Type"},
        {416,  "Range Not Satisfiable"},
        {417,  "Expectation Failed"},
        {418,  "I'm a teapot"},
        {421,  "Misdirected Request"},
        {422,  "Unprocessable Entity"},
        {423,  "Locked"},
        {424,  "Failed Dependency"},
        {425,  "Too Early"},
        {426,  "Upgrade Required"},
        {428,  "Precondition Required"},
        {429,  "Too Many Requests"},
        {431,  "Request Header Fields Too Large"},
        {451,  "Unavailable For Legal Reasons"},
        {501,  "Not Implemented"},
        {502,  "Bad Gateway"},
        {503,  "Service Unavailable"},
        {504,  "Gateway Timeout"},
        {505,  "HTTP Version Not Supported"},
        {506,  "Variant Also Negotiates"},
        {507,  "Insufficient Storage"},
        {508,  "Loop Detected"},
        {510,  "Not Extended"},
        {511,  "Network Authentication Required"}
    };
    auto it = _statu_msg.find(statu);
    if (it != _statu_msg.end())
    {
        return it->second;
    }
    return "UNKNOW";
}

void test_GetStatuDesc()
{
    int statu;
    while (true)
    {
        std::cin >> statu;
        std::cout << GetStatuDesc(statu) << std::endl;
    }
}



std::string GetExtMime(const std::string& file_name)
{
    std::unordered_map<std::string, std::string> _mime_msg = {
        {".aac",        "audio/aac"},
        {".abw",        "application/x-abiword"},
        {".arc",        "application/x-freearc"},
        {".avi",        "video/x-msvideo"},
        {".azw",        "application/vnd.amazon.ebook"},
        {".bin",        "application/octet-stream"},
        {".bmp",        "image/bmp"},
        {".bz",         "application/x-bzip"},
        {".bz2",        "application/x-bzip2"},
        {".csh",        "application/x-csh"},
        {".css",        "text/css"},
        {".csv",        "text/csv"},
        {".doc",        "application/msword"},
        {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
        {".eot",        "application/vnd.ms-fontobject"},
        {".epub",       "application/epub+zip"},
        {".gif",        "image/gif"},
        {".htm",        "text/html"},
        {".html",       "text/html"},
        {".ico",        "image/vnd.microsoft.icon"},
        {".ics",        "text/calendar"},
        {".jar",        "application/java-archive"},
        {".jpeg",       "image/jpeg"},
        {".jpg",        "image/jpeg"},
        {".js",         "text/javascript"},
        {".json",       "application/json"},
        {".jsonld",     "application/ld+json"},
        {".mid",        "audio/midi"},
        {".midi",       "audio/x-midi"},
        {".mjs",        "text/javascript"},
        {".mp3",        "audio/mpeg"},
        {".mpeg",       "video/mpeg"},
        {".mpkg",       "application/vnd.apple.installer+xml"},
        {".odp",        "application/vnd.oasis.opendocument.presentation"},
        {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
        {".odt",        "application/vnd.oasis.opendocument.text"},
        {".oga",        "audio/ogg"},
        {".ogv",        "video/ogg"},
        {".ogx",        "application/ogg"},
        {".otf",        "font/otf"},
        {".png",        "image/png"},
        {".pdf",        "application/pdf"},
        {".ppt",        "application/vnd.ms-powerpoint"},
        {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
        {".rar",        "application/x-rar-compressed"},
        {".rtf",        "application/rtf"},
        {".sh",         "application/x-sh"},
        {".svg",        "image/svg+xml"},
        {".swf",        "application/x-shockwave-flash"},
        {".tar",        "application/x-tar"},
        {".tif",        "image/tiff"},
        {".tiff",       "image/tiff"},
        {".ttf",        "font/ttf"},
        {".txt",        "text/plain"},
        {".vsd",        "application/vnd.visio"},
        {".wav",        "audio/wav"},
        {".weba",       "audio/webm"},
        {".webm",       "video/webm"},
        {".webp",       "image/webp"},
        {".woff",       "font/woff"},
        {".woff2",      "font/woff2"},
        {".xhtml",      "application/xhtml+xml"},
        {".xls",        "application/vnd.ms-excel"},
        {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
        {".xml",        "application/xml"},
        {".xul",        "application/vnd.mozilla.xul+xml"},
        {".zip",        "application/zip"},
        {".3gp",        "video/3gpp"},
        {".3g2",        "video/3gpp2"},
        {".7z",         "application/x-7z-compressed"}
    };
    size_t pos = file_name.find_last_of(".");
    if (pos == std::string::npos) { return "application/octet-stream"; }
    auto it = _mime_msg.find(file_name.substr(pos));
    if (it == _mime_msg.end()) { return "application/octet-stream"; }
    return it->second;
}

void test_GetExtMime()
{
    std::string file_name;
    while (1) 
    {
        std::cin >> file_name;
        std::cout << GetExtMime(file_name) << std::endl;
    }
}



bool IsDirectory(const std::string& file_name)
{
    struct stat st;
    int ret = ::stat(file_name.c_str(), &st);
    if (ret < 0)
    {
        LOG(ERROR, "Util::IsDirectory Get file %s properties error: %d -> %s", file_name.c_str(), errno, strerror(errno));
        return false;
    }
    return S_ISDIR(st.st_mode);
}

// 判断一个文件是否是普通文件
bool IsRegular(const std::string& file_name)
{
    struct stat st;
    int ret = ::stat(file_name.c_str(), &st);
    if (ret < 0)
    {
        LOG(ERROR, "Util::IsRegular Get file %s properties error: %d -> %s", file_name.c_str(), errno, strerror(errno));
        return false;
    }
    return S_ISREG(st.st_mode);
}

void test_FileMode()
{
    std::cout << IsDirectory("any.cc") << std::endl;
    std::cout << IsDirectory("testdir") << std::endl;
    std::cout << IsRegular("testdir") << std::endl;
    std::cout << IsRegular("any.cc") << std::endl;
}



bool IsValidPath(const std::string& path)
{
    int level = 0;
    std::vector<std::string> arr;
    int ret = Split(path, "/", &arr);
    for (auto& e : arr)
    {
        if (e == "..") --level;
        else if (e == ".") continue;
        else ++level;
        if (level < 0) return false;
    }
    return true;
}


void test_IsValidPath()
{
    std::cout << IsValidPath("/html/../index.html/../") << std::endl;
}


int main()
{
    // test_Split();

    // std::string content;
    // test_ReadFile(&content);
    // test_WriteFile(content);

    // test_Url();

    // test_GetStatuDesc();

    // test_GetExtMime();

    // test_FileMode();

    test_IsValidPath();

    return 0;
}